import React, { useState } from 'react';
import { Form, Input, Button, Card, message, Row, Col } from 'antd';
import { UserOutlined, LockOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import axios from 'axios';
import './Login.css';

const Login = () => {
  const [loading, setLoading] = useState(false);
  const navigate = useNavigate();

  const onFinish = async (values) => {
    try {
      setLoading(true);
      const { mobile, password } = values;
      
      // 调用登录接口，使用 GET 请求，参数拼接在 URL 中
      const response = await axios({
        method: 'get',
        url: `http://127.0.0.1:8081/user/login?mobile=${mobile}&password=${password}`,
      });
      
      const { data } = response;
      
      // 处理响应
      if (data.code) {
        // 登录失败，显示错误信息
        message.info(data.msg);
      } else {
        // 登录成功
        message.success('登录成功');
        
        // 保存 token 到 localStorage
        localStorage.setItem('token', data.data.token);
        
        // 跳转到主页
        navigate('/');
      }
    } catch (error) {
      console.info('登录出错:', error);
      message.info('网络错误，请稍后重试');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="login-container">
      <div className="login-form">
        <div className="login-logo">React Antd 管理系统</div>
        <Card className="login-card">
          <div className="login-title">用户登录</div>
          <Form
            name="login"
            initialValues={{ remember: true }}
            onFinish={onFinish}
            size="large"
          >
            <Form.Item
              name="mobile"
              rules={[
                { required: true, message: '请输入手机号' },
                { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确' }
              ]}
            >
              <Input prefix={<UserOutlined />} placeholder="手机号" />
            </Form.Item>

            <Form.Item
              name="password"
              rules={[{ required: true, message: '请输入密码' }]}
            >
              <Input.Password
                prefix={<LockOutlined />}
                placeholder="密码"
              />
            </Form.Item>

            <Form.Item>
              <Button 
                type="primary" 
                htmlType="submit" 
                block 
                loading={loading}
                className="login-form-button"
              >
                登录
              </Button>
            </Form.Item>
          </Form>
        </Card>
      </div>
    </div>
  );
};

export default Login; 